// 云函数入口文件 - 活动报名功能
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { activityId, participants, notes, totalAmount } = event
  
  console.log('收到报名请求:', {
    activityId,
    participants,
    notes,
    totalAmount,
    openid: wxContext.OPENID
  })
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID
  
  // 获取用户信息
  const userResult = await db.collection('users').where({
    _openid: userOpenid
  }).get()
  
  if (userResult.data.length === 0) {
    return {
      success: false,
      message: '用户不存在'
    }
  }
  
  const userInfo = userResult.data[0]
  
  try {
    // 1. 验证用户登录状态
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录，请先登录'
      }
    }
    
    // 2. 验证基本参数
    if (!activityId || !participants || participants.length === 0) {
      return {
        success: false,
        message: '参数不完整：缺少活动ID或参与者信息'
      }
    }
    
    // 3. 验证参与者信息
    for (let i = 0; i < participants.length; i++) {
      const participant = participants[i]
      if (!participant.name || !participant.name.trim()) {
        return {
          success: false,
          message: `第${i + 1}位参与者姓名不能为空`
        }
      }
      if (!participant.phone || !participant.phone.trim()) {
        return {
          success: false,
          message: `第${i + 1}位参与者电话不能为空`
        }
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(participant.phone)) {
        return {
          success: false,
          message: `第${i + 1}位参与者电话格式不正确`
        }
      }
    }
    
    // 4. 检查活动是否存在
    console.log('开始检查活动是否存在，活动ID:', activityId)
    const activityResult = await db.collection('activities').doc(activityId).get()
    if (!activityResult.data) {
      console.error('活动不存在:', activityId)
      return {
        success: false,
        message: '活动不存在或已下架'
      }
    }
    
    const activity = activityResult.data
    console.log('活动信息:', {
      id: activity._id,
      title: activity.eventTitle || activity.title,
      price: activity.price,
      maxParticipants: activity.maxParticipants
    })
    
    // 5. 检查参与者是否已报名
    console.log('开始检查参与者是否已报名')
    const existingMembers = await db.collection('activity_members')
      .where({
        activityId: activityId
      })
      .get()
    
    console.log(`查询到${existingMembers.data.length}个已报名成员`)
    
    // 创建已报名参与者映射（姓名+电话作为唯一标识）
    const existingParticipantMap = new Map()
    existingMembers.data.forEach(member => {
      const key = `${member.name}_${member.phone}`
      existingParticipantMap.set(key, member)
    })
    
    console.log('已报名参与者映射:', Array.from(existingParticipantMap.keys()))
    
    // 分类参与者：新参与者 vs 已存在参与者
    const newParticipants = []
    const existingParticipants = []
    
    participants.forEach(participant => {
      const key = `${participant.name}_${participant.phone}`
      if (existingParticipantMap.has(key)) {
        console.log(`参与者${participant.name}(${participant.phone})已存在`)
        existingParticipants.push(participant)
      } else {
        console.log(`参与者${participant.name}(${participant.phone})为新参与者`)
        newParticipants.push(participant)
      }
    })
    
    console.log(`分类结果: ${newParticipants.length}位新参与者, ${existingParticipants.length}位已存在`)
    
    // 如果所有参与者都已报名，直接返回
    if (newParticipants.length === 0) {
      console.log('所有参与者都已报名，返回失败')
      
      // 构建已报名参与者的详细列表
      const participantNames = existingParticipants.map(p => p.name).join('、');
      
      return {
        success: false,
        message: `以下参与者已报名该活动：${participantNames}`,
        existingParticipants: existingParticipants,
        skipCount: existingParticipants.length,
        detailMessage: existingParticipants.length === 1 ? 
          `${existingParticipants[0].name}(${existingParticipants[0].phone})已经报名了该活动` :
          `${participantNames} 已经报名了该活动，请更换其他参与者`
      }
    }
    
    // 6. 验证金额计算（基于新参与者数量）
    const expectedAmount = newParticipants.length * (activity.price || 0)
    if (totalAmount !== expectedAmount) {
      return {
        success: false,
        message: `金额计算错误，应为¥${expectedAmount}（基于${newParticipants.length}位新参与者）`
      }
    }
    
    const now = new Date()
    
    // 7. 用户信息已经在前面获取了
    console.log('使用用户信息:', userInfo._id)
    
    // 8. 开始事务处理
    const transaction = await db.startTransaction()
    
    try {
      // 8.1 创建报名记录
      const registrationResult = await transaction.collection('activity_registrations').add({
        data: {
          activityId: activityId,
          registrantId: userOpenid,
          participants: newParticipants, // 只记录新参与者
          originalParticipants: participants, // 记录原始所有参与者
          existingParticipants: existingParticipants, // 记录已存在的参与者
          registrationTime: now,
          status: 1,
          paymentStatus: 'paid',
          totalAmount: totalAmount,
          notes: notes || '',
          createdAt: now,
          updatedAt: now
        }
      })
      
      console.log('报名记录创建成功:', registrationResult._id)
      
      // 8.2 添加参与者到活动成员表
      const memberPromises = newParticipants.map(participant => {
        return transaction.collection('activity_members').add({
          data: {
            activityId: activityId,
            registrantId: userOpenid,
            registrationId: registrationResult._id,
            name: participant.name,
            phone: participant.phone,
            createdAt: now
          }
        })
      })
      
      await Promise.all(memberPromises)
      console.log(`成功添加${newParticipants.length}个新参与者到活动成员表`)
      
      // 8.3 微信支付场景下，返现逻辑移至支付回调处理
      // 这里不再处理余额增加，由activityPayNotify处理
      
      // 8.4 更新用户活动中继表
      const userActivityResult = await transaction.collection('user_activity_relay').where({
        userId: userOpenid
      }).get()
      
      if (userActivityResult.data.length > 0) {
        // 更新现有记录
        const userActivity = userActivityResult.data[0]
        const activityRecords = userActivity.activityRecords || []
        activityRecords.push({
          activityId: activityId,
          status: 'registered',
          registrationTime: now,
          paymentStatus: 'paid'
        })
        
        await transaction.collection('user_activity_relay').doc(userActivity._id).update({
          data: {
            activityRecords: activityRecords,
            updatedAt: now
          }
        })
        console.log('更新用户活动中继表记录')
      } else {
        // 创建新记录
        await transaction.collection('user_activity_relay').add({
          data: {
            userId: userOpenid,
            activityRecords: [{
              activityId: activityId,
              status: 'registered',
              registrationTime: now,
              paymentStatus: 'paid'
            }],
            createdAt: now,
            updatedAt: now
          }
        })
        console.log('创建新的用户活动中继表记录')
      }
      
      // 提交事务
      await transaction.commit()
      console.log('事务提交成功')
      
      return {
        success: true,
        message: `报名成功！${newParticipants.length}位新参与者已添加${existingParticipants.length > 0 ? `，跳过${existingParticipants.length}位已报名参与者` : ''}`,
        data: {
          _id: registrationResult._id,
          totalAmount: totalAmount,
          newParticipantsCount: newParticipants.length,
          skippedParticipantsCount: existingParticipants.length,
          newParticipants: newParticipants,
          existingParticipants: existingParticipants,
          // 返现逻辑移至支付回调处理
        }
      }
      
    } catch (transactionError) {
      // 回滚事务
      await transaction.rollback()
      console.error('事务处理失败:', transactionError)
      return {
        success: false,
        message: '报名处理失败：' + (transactionError.message || '请重试')
      }
    }
    
  } catch (error) {
    console.error('报名失败详细错误:', error)
    console.error('错误堆栈:', error.stack)
    
    return {
      success: false,
      message: '报名失败: ' + error.message,
      errorCode: error.errCode,
      errorDetail: error.toString()
    }
  }
}